import axios from 'axios'
import router from '@/router'
import type { AdminInfo } from '@/types/admin'
import { useUserStore } from '@/stores'
import { ElMessage } from 'element-plus'

// 基地址
const baseURL = 'http://127.0.0.1:3007/api'
const instance = axios.create({
  baseURL,
  timeout: 10000
})
const userStore = useUserStore()

// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    if (userStore.userInfo?.token) {
      config.headers.Authorization = userStore.userInfo?.token
    }
    return config
  },
  (err) => Promise.reject(err)
)

// 响应拦截器
instance.interceptors.response.use(
  (res) => {
    if (res.data.status === 200) {
      return res.data
    }
    ElMessage({
      message: res.data.message || '服务异常',
      type: 'error'
    })
    return Promise.reject(res.data)
  },
  (err) => {
    if (err.response.status === 401) {
      userStore.setUserInfo({} as AdminInfo)
      router.push('/login')
      ElMessage({
        message: '身份认证失败',
        type: 'error'
      })
      return Promise.reject(err)
    }
    ElMessage({
      message: err.response.data.message || '服务异常',
      type: 'error'
    })
    return Promise.reject(err)
  }
)

export default instance
